import React, { use, useEffect, useState } from 'react';
import { ScrollView, View, Alert, Modal, TextInput, TouchableOpacity, StyleSheet, Text} from 'react-native';
import UserCard from '@/components/features/device/UserCard';
import ProfileEditor from '@/components/features/device/ProfileEditor';
import ButtonDemo from '@/components/features/device/ButtonDemo';
import FamilyCard from '@/components/features/device/FamilyCard';
import { router } from 'expo-router';
import { useFocusEffect } from 'expo-router';
import { createFamily, generateInviteCode, joinFamily, getFamilyMembers } from '../../api/family';
import { registerUser, loginUser, logoutUser, refreshToken, getUserProfile, changePassword } from '../../api/auth';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { WhiteSpace } from '@ant-design/react-native';

type FamilyMember = {
    id: number;
    username: string;
    family_name: string;
    role: string; // 例如 'owner', 'member'
    joined_at: string; // 加入时间
};

export default function BlankScreen() {
    const [profile, setProfile] = useState({
        nickname: '',
        phone: '',
        username: '',
        // password: '没有返回密码api',
    });
    const [members, setMembers] = useState<FamilyMember[]>([]);
    const [modalVisible, setModalVisible] = useState(false);
    const [oldPassword, setOldPassword] = useState('');
    const [newPassword, setNewPassword] = useState('');

    useFocusEffect(
        React.useCallback(() => {
            fetchUserProfile();
            fetchFamilyMembers();   
        }, [])
    );

    useEffect(() => {
        fetchUserProfile();
        fetchFamilyMembers();
    }, []);

    const fetchFamilyMembers = async () => {
        try {
            const response = await getFamilyMembers();
            setMembers(response.data);
            setProfile(prev => ({ ...prev, familyName: response.data[0]?.family_name || '' }));
            console.log('获取家庭成员成功:', response.data);
        } catch (error) {
            console.error('获取家庭成员失败:', error);
        }
    };

    const fetchUserProfile = async () => {
        try {
            const response = await getUserProfile();
            setProfile({
                nickname: response.data.nickname,
                phone: response.data.username,
                username: response.data.username,
                // password: response.data.password,
            });
            console.log('获取用户信息成功:', response.data);
        } catch (error) {
            console.error('获取用户信息失败:', error);
        }
    };

    const handleChangePassword = async (old_password: string, new_password: string) => {
        if (!oldPassword || !newPassword) {
            alert('请输入当前密码和新密码');
            return;
        }
        try {
            const response = await changePassword({
                old_password,
                new_password,
            });
            if(response.data.ok){
                alert('密码修改成功');
                setModalVisible(false);
            }
            else{
                alert('密码修改失败');
            }
        } catch (error: any) {
            console.error('修改密码失败:', error);
            alert(error.response?.data?.message || '修改密码失败');
        }
    };

    const handleLogout = async () => {
        try {
            const currentRefreshToken = await AsyncStorage.getItem('refresh_token');
            if (!currentRefreshToken) {
                Alert.alert('错误', '未找到刷新令牌');
                return;
            }

            // 调用登出接口
            await logoutUser({ refresh: currentRefreshToken });

            // 清除本地 token
            await AsyncStorage.removeItem('access_token');
            await AsyncStorage.removeItem('refresh_token');

            Alert.alert('退出成功', '已成功退出登录');

            // 跳转到登录页（请根据实际路由调整）
            router.replace('../FirstPage'); // 或 '/auth/login' 等
        } catch (error: any) {
            console.error('退出失败:', error); // 打印错误日志
            Alert.alert('错误', error.response?.data?.message || '退出失败，请重试');
        }      
    };

    const handleSave = () => {
        alert(
            `保存信息: 昵称: ${profile.nickname}\n手机号: ${profile.phone}`
        );
    };

    // const handle

    return (
        <View style={{ flex: 1 }}>
            <ScrollView style={{ flex: 1, backgroundColor: '#fff' }}>
                <View style={{ alignItems: 'center', marginTop: 60 }}>
                    <UserCard
                        // avatar={require('../../assets/images/VaccumCleaner.jpg')}
                        username={profile.username || '用户名'}
                        nickname={profile.nickname || '昵称'}
                        // onEditPress={() => router.push('/ProfileEditor')
                    />
                    <FamilyCard
                        familyName="家庭"
                        memberCount={members.length}
                        onAddPress={() => router.push('/FamilyPage')}
                    />
                    <ProfileEditor
                        fields={['nickname', 'phone']}
                            initialPhone={profile.phone}
                            initialNickname={profile.nickname}
                            // initialPassword={profile.password}
                        onChange={data => setProfile(prev => ({ ...prev, ...data }))}
                    />
                    {/* <ButtonDemo
                        onPress={() => {}}
                        text="保存信息"
                    /> */}
                    <WhiteSpace size='lg'/>
                    <ButtonDemo
                        onPress={() => setModalVisible(true)} 
                        text="修改密码"
                    />
                    <WhiteSpace size='lg'/>
                    <ButtonDemo
                        onPress={handleLogout}
                        text="退出登录"
                        textColor="#e60000"
                    />
                    {/* <ButtonDemo
                        onPress={handleLogout}
                        text="退出登录"
                        textColor="#fff"
                    /> */}
                    {/* <ButtonDemo
                        onPress={() => router.push('../index')}
                        text=""
                        textColor="#fff"
                        test={true}
                    /> */}
                    <Text
                        onPress={() => {
                            router.replace('/FirstPage');
                        }}
                        style={{
                            padding: 20,
                            color: '#fff',
                        }}
                    >
                        Start
                    </Text>
    </View>
            </ScrollView>
            <Modal
                animationType="fade"
                transparent={true}
                visible={modalVisible}
                onRequestClose={() => {
                    setModalVisible(false);
                    setOldPassword('');
                    setNewPassword('');
                }}
            >
                <View style={styles.modalOverlay}>
                    <View style={styles.modalContainer}>
                        <Text style={styles.modalTitle}>修改密码</Text>

                        <TextInput
                            style={styles.input}
                            placeholder="当前密码"
                            secureTextEntry
                            value={oldPassword}
                            onChangeText={setOldPassword}
                        />

                        <TextInput
                            style={styles.input}
                            placeholder="新密码"
                            secureTextEntry
                            value={newPassword}
                            onChangeText={setNewPassword}
                        />

                        <View style={styles.modalButtons}>
                            <TouchableOpacity
                                style={[styles.button, styles.cancelButton]}
                                onPress={() => {
                                    setModalVisible(false);
                                    setOldPassword('');
                                    setNewPassword('');
                                }}
                            >
                                <Text style={styles.buttonText}>取消</Text>
                            </TouchableOpacity>

                            <TouchableOpacity
                                style={[styles.button, styles.confirmButton]}
                                onPressIn={() => handleChangePassword(oldPassword, newPassword)}
                            >
                                <Text style={styles.buttonText}>确定</Text>
                            </TouchableOpacity>
                        </View>
                    </View>
                </View>
            </Modal>
        </View>
    );
}

const styles = StyleSheet.create({
    modalOverlay: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: 'rgba(0, 0, 0, 0.5)',
    },
    modalContainer: {
        width: 300,
        padding: 20,
        backgroundColor: 'white',
        borderRadius: 10,
        alignItems: 'center',
    },
    modalTitle: {
        fontSize: 18,
        fontWeight: 'bold',
        marginBottom: 15,
    },
    input: {
        width: '100%',
        borderWidth: 1,
        borderColor: '#ccc',
        padding: 10,
        marginBottom: 15,
        borderRadius: 5,
    },
    modalButtons: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        width: '100%',
    },
    button: {
        flex: 1,
        padding: 10,
        borderRadius: 5,
        alignItems: 'center',
    },
    cancelButton: {
        backgroundColor: '#999',
        marginRight: 10,
    },
    confirmButton: {
        backgroundColor: '#e60000',
    },
    buttonText: {
        color: '#fff',
        fontWeight: 'bold',
    },
});